package com.atguigu.service.impl;

import com.atguigu.base.BaseMapper;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.entity.Permission;
import com.atguigu.entity.Role;
import com.atguigu.mapper.AdminRoleMapper;
import com.atguigu.mapper.PermissionMapper;
import com.atguigu.mapper.RoleMapper;
import com.atguigu.mapper.RolePermissionMapper;
import com.atguigu.service.RoleService;
import javafx.beans.binding.MapExpression;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Date:2022/10/29
 * Author:ybc
 * Description:
 */
@DubboService
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    //用户角色信息增删改查
    @Autowired
    private RoleMapper roleMapper;
    //权限显示
    @Autowired
    private PermissionMapper permissionMapper;
    //权限分配
    @Autowired
    private RolePermissionMapper rolePermissionMapper;


    @Override
    public BaseMapper<Role> getBaseMapper() {
        return roleMapper;
    }


    @Override
    public List<Map<String, Object>> findZNodes(Long roleId) {
        //获取所有的权限信息
        List<Permission> allPermissionList = permissionMapper.findAll();
        //获取当前角色所拥有的权限id的集合
        List<Long> permissionIdList = rolePermissionMapper.findPermissionIdListByRoleId(roleId);
        //创建存储节点数据的集合,节点数据是一个键值对组成的元素，有多个用List
         List<Map<String,Object>> zNodes= new ArrayList<>();
        for (Permission permission : allPermissionList) {
            Map<String,Object> zNode = new HashMap<>();
            zNode.put("id",permission.getId());
            zNode.put("pId",permission.getParentId());
            zNode.put("name",permission.getName());
            if (permissionIdList.contains(permission.getId())){
                zNode.put("checked",true);
            }else {
                zNode.put("checked",false);
            }
            zNodes.add(zNode);
        }
        return zNodes;
    }

    @Override
    public void assignPermission(Long roleId, List<Long> permissionIds) {
        //将中间表中角色和权限的关系删除
        rolePermissionMapper.deleteByRoleId(roleId);
        //为角色重新分配权限
        rolePermissionMapper.assignPermission(roleId, permissionIds);
    }
}
